package util;

import common.DataAnalysis;
import net.sf.json.JSONObject;
import util.mysql.MysqlUtil;
import util.remote.RemoteConf;
import util.remote.RemoteConnectResult;

import java.sql.Connection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 活动配置类
 * @see DataAnalysis#DataAnalysis(RemoteConnectResult, String)
 * 在数据分析器 构造器中会自动根据confCode 查询相应配置 并放到
 * @see #conf 中
 * 实现了几个常用的方法
 * @see #getActTimeStartStr() 没有横线的字符串时间
 * @see #getTimeStartStr() 有横线的字符串时间
 * @see #getTimeStart() 活动开始时间
 * @see #getTimeEnd() 活动结束时间
 *
 *
 *
 * Created by J.Chen on 2017/5/19.
 */
public class ActConf {

    private String confCode;
    private JSONObject conf;
    //活动是否存在
    private boolean isExsits = false;

    public JSONObject getConf() {
        return conf;
    }

    public String getConfCode() {
        return confCode;
    }


    public ActConf initConf(RemoteConf conf, MysqlUtil mysqlUtil, String confCode) {
        this.confCode = confCode;
        initConf(mysqlUtil.selectOne( String.format("SELECT *  FROM com_conf%s where conf_code='%s'", conf.isDuowan() ? "$duowan" : "", confCode)).get("content"));
        return this;
    }

    /**
     * 返回活动名称
     *
     * 配置了actName属性的返回该属性 否则返回confCode
     *
     * @return
     */
    public String getActName(){
        if(isExsits() && conf.containsKey("actName")){
            return conf.getString("actName");
        }
        return confCode;
    }

    public boolean isExsits() {
        return isExsits;
    }

    private ActConf initConf(String content) {
        if (content != null) {
            isExsits = true;
            conf = JSONObject.fromObject(content);
        }
        return this;
    }


    public Date getTimeStart() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(conf.getString("timeStart"));
        } catch (ParseException e) {
            return null;
        }
    }

    public String getTimeStartStr() {
        return conf.getString("timeStart").substring(0, 10);
    }

    public String getActTimeStartStr() {
        return conf.getString("timeStart").substring(0, 10).replaceAll("-","");
    }

    public Date getTimeEnd() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(conf.getString("timeEnd"));
        } catch (ParseException e) {
            return null;
        }
    }
}
